﻿

#region Using directives

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UFIDA.U9.Cust.SH.SHFastShipSV.Proxy;
using UFIDA.U9.Cust.SH.SHFastShipBP.Proxy;
using UFIDA.U9.Cust.SH.SHFastShipBP;
using UFSoft.UBF.PL.Engine;
using UFIDA.U9.CBO.HR.Department;
using UFSoft.UBF.Business;
using UFIDA.U9.Base;
using UFIDA.U9.SM.Enums;
using UFIDA.U9.Base.Sequence;
using UFIDA.U9.CBO.SCM.Item;
using System.Data;
using UFIDA.U9.Cust.SH.SHFastShipKitItemBE;
using UFIDA.U9.Cust.SH.SHFastShipBE.SHFastShipBE;
using UFSoft.UBF.Util.DataAccess;
using UFIDA.U9.CBO.SCM.Warehouse;

#endregion

namespace UFIDA.U9.Cust.SH.SHFastShipBE {

	public partial class SHFastShip{

		#region Custom Constructor

		#endregion

		#region before & after CUD V 
		/*	实体提交的事件顺序示例(QHELP) 主实体A 组合 非主实体B .
		/ (新增A和B两个实例)A.OnSetDefaultValue->B.OnSetDefaultValue-> B.OnValidate ->A.OnValidate ->A.OnInserting ->B.OnInserting ->产生提交SQL ->B.OnInserted ->A.OnInserted
		/ (仅修改B,A也会被修改))A.OnSetDefaultValue->B.OnSetDefaultValue-> B.OnValidate ->A.OnValidate ->A.OnUpdating ->B.OnUpdating ->产生提交SQL ->B.OnUpdated ->A.OnUpdated
		/ (删除A,B会被级联删除))A.OnDeleting ->B.OnDeleting ->产生提交SQL ->B.OnDeleted ->A.OnDeleted
		/	产生提交SQL顺序则看其外键，增修一对多先A后B，一对一先B后A。　删除一对多先B后A，一对一先A后B .
		*/	
		/// <summary>
		/// 设置默认值
		/// </summary>
        protected override void OnSetDefaultValue()
        {
            base.OnSetDefaultValue();

            //设置单号
            SetDocNo();

            //设置默认部门
            if (this.DeptKey == null)
            {
                Department dept = Department.Finder.Find("Org=" + Context.LoginOrg.ID + " order by Code");
                if (dept == null)
                    throw new Exception("查找部门失败，部门编码:" + this.Customer.DescFlexField.PrivateDescSeg6);
                this.DeptKey = dept.Key;
            }

            //设置是否直运
            //this.IsZY = this.Customer.DescFlexField.PrivateDescSeg8 == "True" ? true : false;
            
            //依据销售订单,设置直运客户,资源仓库
            foreach (SHFastShipLine line in this.SHFastShipLine)
            {
                if (line.SOLineKey != null)
                {
                    if (!string.IsNullOrEmpty(line.SOLine.SO.DescFlexField.PubDescSeg16))
                    {
                        string opath = " Org={0} and Code='{1}'";
                        opath = string.Format(opath, Context.LoginOrg.ID, line.SOLine.SO.DescFlexField.PubDescSeg16);
                        UFIDA.U9.CBO.SCM.Customer.Customer cu = UFIDA.U9.CBO.SCM.Customer.Customer.Finder.Find(opath);
                        if (cu == null)
                            throw new Exception("订单号：" + line.SOLine.SO.DocNo+ "直运客户设置错误，请检查！");
                        this.ZYCustomerKey = cu.Key;
                        this.IsZY = true;

                        if (!string.IsNullOrEmpty(this.Customer.DescFlexField.PrivateDescSeg10))
                        {
                            Warehouse wh = Warehouse.Finder.Find(" Code='" + this.Customer.DescFlexField.PrivateDescSeg10 + "'");
                            if (wh == null)
                                throw new Exception("依据客户查找仓库失败，仓库编码：" + this.Customer.DescFlexField.PrivateDescSeg10);
                            this.SaleWHKey = wh.Key;
                        }
                        break;
                    }
                }
            }

            //设置淘宝总金额
            if (this.DocType.Code == "U914")
            {
                SetTBAmount();
            }

        }

		/// <summary>
		/// before Insert
		/// </summary>
		protected override void OnInserting() {
			base.OnInserting();
			// TO DO: write your business code here...

            //设置信用免检
            if (this.DocType.CreditCheckTime == SDCreditCheckTimeEnum.NotCheck)
                this.CreditNoCheck = true;
            else
                this.CreditNoCheck = false;
            
            //快速发货取价
            List<SHFastShipLine> pricelines = new List<SHFastShipLine>();
            foreach (SHFastShipLine line in this.SHFastShipLine)
            {
                if (line.SOLineKey == null)
                {
                    pricelines.Add(line);
                }
            }
            SetPrice(pricelines);

            List<SHFastShipLine> alllines = new List<SHFastShipLine>();
            foreach (SHFastShipLine line in this.SHFastShipLine)
            {
                alllines.Add(line);
            }
            SetMoney(alllines);
            SetTotalMoney();
		}

        private void BuildReserveSQLNotKit(ref List<string> batchsql)
        {
            foreach (SHFastShipLine line in this.SHFastShipLine)
            {
                if(line.Item.ItemFormAttribute != ItemTypeAttributeEnum.Kit)
                {
                    long lotid = 0;
                    if (line.LotMasterKey != null) lotid = line.LotMasterKey.ID;
                    string sql=BuildReserveSQL(line.ItemKey.ID, line.WHKey.ID, lotid, line.Qty);
                    batchsql.Add(sql);
                }
            }
        }

        private void BatchRunSQL(List<string> batchsql)
        {
            int total = 100;
            int cnt = 0;
            StringBuilder runsql = new StringBuilder();

            if (batchsql.Count <= 0) return;
            foreach (string sql in batchsql)
            {
                if (string.IsNullOrEmpty(sql)) continue;
                cnt++;
                runsql.AppendLine(sql);
                runsql.AppendLine();
                if (cnt >= total)
                {
                    DataAccessor.RunSQL(DataAccessor.GetConn(), runsql.ToString(), null);
                    runsql.Length = 0 ;
                }
            }
            if (runsql.Length > 0)
            {
                DataAccessor.RunSQL(DataAccessor.GetConn(), runsql.ToString(), null);
            }
        }

        private void BatchCreateKitItem(List<SHFastShipLine> lines, ref List<string> batchsql)
        {
            if (lines.Count <= 0) return;
            string itemcodes = GetItemCodes(lines);
            DataTable bomdt = GetBOMComponent(itemcodes);
            foreach (SHFastShipLine line in lines)
            {
                DataRow[] subitems = GetItemBOMComponent(bomdt, line.Item.Code);
                foreach (DataRow row in subitems)
                {
                    SHFastShipKitItem kititem = SHFastShipKitItem.Create();
                    kititem.SHFastShipLineKey = line.Key;

                    //料品依据组织需要转换
                    ItemMaster item = null;
                    if (Context.LoginOrg.Code == "1000")
                    {
                        //双虎组织不用转换
                        long itemid = PubTool.ToLong(row["subitem"].ToString());
                        item = ItemMaster.Finder.FindByID(itemid);
                        if (item == null) throw new Exception("查找料品失败，料品编码：" + row["subcode"].ToString());
                    }
                    else
                    {
                        //经销商组织需要转换
                        item = ItemMaster.Finder.Find("Org=" + Context.LoginOrg.ID + " and Code='" + row["subcode"].ToString() + "'");
                        if (item == null) throw new Exception("查找经销商组织料品失败，料品编码：" + row["subcode"].ToString());

                    }

                    kititem.ItemKey = item.Key;
                    kititem.Qty = PubTool.ToDecimal( row["usage"].ToString()) * line.Qty;

                    //子件仓库默认逻辑
                    if (line.WHKey == line.Item.SaleInfo.ShipmentWarehouseKey)
                    {
                        kititem.WHKey = item.SaleInfo.ShipmentWarehouseKey;
                    }
                    else
                    {
                        kititem.WHKey = line.WHKey;
                    }

                    long lotid = 0;
                    if (line.LotMasterKey != null) lotid = line.LotMasterKey.ID;
                    string sql=BuildReserveSQL(kititem.ItemKey.ID, kititem.WHKey.ID, lotid, kititem.Qty);
                    batchsql.Add(sql);
                }
            }
        }

        private string BuildReserveSQL(long itemid, long wh, long lot, decimal qty)
        {
            if (qty == 0) return "";

            ItemMaster item = ItemMaster.Finder.FindByID(itemid);
            if (item == null) throw new Exception("查找料品出错！");

            string sql = "";
            if (qty > 0)
            {
                sql = @"Update InvTrans_WhQoh set ResvStQtyCU=
                    case when (isnull(ResvStQtyCU,0)+{0})<StoreQty then (isnull(ResvStQtyCU,0)+{0}) else StoreQty end";
                sql = string.Format(sql, qty.ToString());
            }
            else if (qty < 0)
            {
                sql = @"Update InvTrans_WhQoh set ResvStQtyCU = 
                    case when (isnull(ResvStQtyCU,0)-{0})>0 then (isnull(ResvStQtyCU,0)-{0}) else 0 end";
                sql = string.Format(sql, Math.Abs(qty).ToString());
            }
            sql += " where 1=1";
            sql += " and ItemInfo_ItemCode='" + item.Code + "'";
            sql += " and wh=" + wh;
            if (lot > 0)
                sql += " and LotInfo_LotMaster_EntityID=" + lot;

            return sql;
        }

        private DataRow[] GetItemBOMComponent(DataTable bomdt, string itemcode)
        {
            DataRow[] rows=bomdt.Select("kitcode='"+itemcode+"'");
            if (rows.Length <= 0) throw new Exception("料号："+itemcode+"不存在BOM！");
            return rows;
        }



        private string GetItemCodes(List<SHFastShipLine> lines)
        {
            string itemcodes = "";
            foreach (SHFastShipLine line in lines)
            {
                string code = line.Item.Code;
                itemcodes += "'"+code + "',";
            }
            if(itemcodes.Length>0)
                itemcodes=itemcodes.Substring(0,itemcodes.Length-1);
            return itemcodes;
        }

        private DataTable GetBOMComponent(string itemcodes)
        {
            //select mas.ItemMaster item,comp.ItemMaster kititem,comp.UsageQty
            //    from CBO_BOMComponent comp
            //    join CBO_BOMMaster mas on mas.ID=comp.BOMMaster
            //    where mas.EffectiveDate<='2012-03-29 00:00:00.000' 
            //        and mas.DisableDate>='2012-03-29 00:00:00.000'
            //        and comp.IsEffective=1
            //        and comp.EffectiveDate<='2012-03-29 00:00:00.000'
            //        and comp.DisableDate>='2012-03-29 00:00:00.000'
            //        and mas.ItemMaster=1001106080381930

            if (string.IsNullOrEmpty(itemcodes)) return null;
            string sql = @"select mas.ItemMaster kititem,item.Code kitcode,comp.ItemMaster subitem
	                        ,item1.Code subcode,comp.UsageQty usage
                                from CBO_BOMComponent comp
                                join CBO_BOMMaster mas on mas.ID=comp.BOMMaster
                                join CBO_ItemMaster item on mas.ItemMaster=item.id
                                join CBO_ItemMaster item1 on comp.ItemMaster=item1.ID";
            sql += " where 1=1";
            sql += " and mas.EffectiveDate<='" + Context.LoginDate + "'";
            sql += " and mas.DisableDate>='" + Context.LoginDate + "'";
            sql += " and comp.IsEffective=1";
            sql += " and comp.EffectiveDate<='" + Context.LoginDate + "'";
            sql += " and comp.DisableDate>='" + Context.LoginDate + "'";
            sql += " and item.Code in (" + itemcodes + ")";
            //只查双虎组织
            sql += " and mas.Org=1001106046291924";
            sql += " and mas.Status=2";
            DataSet ds = new DataSet();

            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out ds);
            if (ds.Tables.Count <= 0) throw new Exception("批量查找BOM出错!");
            return ds.Tables[0];
        }


        private void SetTotalMoney()
        {
            this.TotalAmount = 0;
            foreach (SHFastShipLine line in this.SHFastShipLine)
            {
                //表头总金额
                this.TotalAmount += line.Amount;
            }
        }

        private void SetTBAmount()
        {
            this.TBAmount = 0;
            foreach (SHFastShipLine line in this.SHFastShipLine)
            {
                //表头总金额
                this.TBAmount += line.FinalAmount;
            }
        }

        private void SetDocNo()
        {
            if (string.IsNullOrEmpty(this.DocNo))
            {
                string prefix = "";

                SequenceSegment.EntityList list = SequenceSegment.Finder.FindAll("SequenceDef=" + this.DocType.DocHeaderSequenceKey.ID + " order by IndexNumber", null);
                foreach (SequenceSegment line in list)
                {
                    if (line.SegmentType == SegmentTypesEnum.Constant)
                        if (Context.LoginOrg.Code == "1000" && (this.DocType.Code != "U904" && this.DocType.Code != "U909"))
                            prefix += "FH";
                        else
                            prefix += line.SegmentValue;
                    if (line.SegmentType == SegmentTypesEnum.FieldValue)
                        prefix += this.DocDate.ToString("yyMM");
                }

                GetDocNoProxy proxy = new GetDocNoProxy();
                proxy.Prefix = prefix;
                string docno = proxy.Do();
                this.DocNo = docno;
            }
        }	

        private void SetMoney(List<SHFastShipLine> lines)
        {
            foreach (SHFastShipLine line in lines)
            {
                line.ProductCost = line.ProductPrice * line.Qty;
                line.MarkCost = line.MarkPrice * line.Qty;
                line.TransportCost = line.TransportPrice * line.Qty;
                line.StoreCost = line.StorePrice * line.Qty;
                line.Amount = line.Price * line.Qty;
            }
        }

        private void SetPrice(List<SHFastShipLine> lines)
        {
            //if (lines.Count <= 0) return;

            //List<long> itemids = new List<long>();
            //foreach (SHFastShipLine line in lines)
            //{
            //    if (itemids.Contains(line.ItemKey.ID)) continue;
            //    itemids.Add(line.ItemKey.ID);
            //}

            //GetPriceProxy proxy1 = new GetPriceProxy();
            //proxy1.CustomerID = this.CustomerKey.ID;
            //proxy1.ItemIDS = itemids;
            //proxy1.ZY = this.IsZY;
            //List<PriceDTOData> pricedtos = proxy1.Do();

            //Dictionary<long, PriceDTOData> prices = new Dictionary<long, PriceDTOData>();
            //foreach (PriceDTOData dto in pricedtos)
            //{
            //    if (prices.ContainsKey(dto.ItemID)) continue;
            //    prices.Add(dto.ItemID, dto);
            //}

            //foreach (SHFastShipLine line in lines)
            //{
            //    if (prices.ContainsKey(line.ItemKey.ID))
            //    {
            //        PriceDTOData price = prices[line.ItemKey.ID] as PriceDTOData;
            //        line.Price = price.Price;
            //        line.PriceType = price.PriceType;

            //        line.ProductPrice = price.ProductCost;
            //        line.MarkPrice = price.MarkCost;
            //        line.TransportPrice = price.TransportCost;
            //        line.StorePrice = price.StoreCost;
                    
            //    }
            //}
        }

        private void SetCredit()
        {
            //GetCustomerCreditSVProxy proxy = new GetCustomerCreditSVProxy();
            //proxy.CustomerID = this.CustomerKey.ID;
            ////取 双虎组织 信用余额
            //this.Credit = proxy.Do(1001106046291924);
        }

		/// <summary>
		/// after Insert
		/// </summary>
		protected override void OnInserted() {
			base.OnInserted();
			// TO DO: write your business code here...

            using (ISession session = Session.Open())
            {
                //批量生成Kit子件
                List<SHFastShipLine> kitlines = new List<SHFastShipLine>();
                foreach (SHFastShipLine line in this.SHFastShipLine)
                {
                    if (line.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
                        kitlines.Add(line);
                }
                List<string> batchsql = new List<string>();
                BatchCreateKitItem(kitlines, ref batchsql);
                BuildReserveSQLNotKit(ref batchsql);
                if (batchsql.Count > 0)
                    BatchRunSQL(batchsql);

                BatchUpdateSOLine();

                session.Commit();
            }
		}

		/// <summary>
		/// before Update
		/// </summary>
        protected override void OnUpdating()
        {
            base.OnUpdating();
            // TO DO: write your business code here...

            using (ISession session = Session.Open())
            {
                //设置信用免检
                if (this.DocTypeKey.ID != this.OriginalData.DocTypeKey.ID)
                {
                    if (this.DocType.CreditCheckTime == SDCreditCheckTimeEnum.NotCheck)
                        this.CreditNoCheck = true;
                    else
                        this.CreditNoCheck = false;
                }

                //双虎取价
                List<SHFastShipLine> lines = new List<SHFastShipLine>();
                foreach (SHFastShipLine line in this.SHFastShipLine)
                {
                    if (NeedGetPrice(line))
                    {
                        lines.Add(line);
                    }
                }
                SetPrice(lines);

                //重新刷新金额
                List<SHFastShipLine> lines1 = new List<SHFastShipLine>();
                foreach (SHFastShipLine line in this.SHFastShipLine)
                {
                    if (NeedGetMoney(line))
                    {
                        lines1.Add(line);
                    }
                }
                SetMoney(lines1);

                session.Commit();
            }

            //本表修改，不能放在Session中
            SetTotalMoney();

        }

        private void SetAvailableQty(List<SHFastShipLine> qtylines)
        {
            //List<ItemQryDTOData> list = new List<ItemQryDTOData>();
            //List<ItemInfoDTOData> retlist = new List<ItemInfoDTOData>();

            //foreach (SHFastShipLine line in qtylines)
            //{
            //    ItemQryDTOData dto = new ItemQryDTOData();
            //    dto.CustID = this.CustomerKey.ID;
            //    dto.ItemID = line.ItemKey.ID;
            //    dto.WH = line.WHKey.ID;
            //}

            //if (list.Count > 0)
            //{
            //    GetAvailableQtyProxy proxy = new GetAvailableQtyProxy();
            //    proxy.ItemList = list;
            //    retlist=proxy.Do();
            //}

            //if (retlist.Count > 0)
            //{
            //    Dictionary<long, ItemInfoDTOData> itemdict = new Dictionary<long, ItemInfoDTOData>();
            //    foreach (ItemInfoDTOData dto in retlist)
            //    {
            //        itemdict.Add(dto.ItemID, dto);
            //    }

            //    foreach (SHFastShipLine line in qtylines)
            //    {
            //        line.StoreQty = itemdict[line.ItemKey.ID].Qty;
            //        line.AvailableQty = itemdict[line.ItemKey.ID].AvailableQty;
            //    }
            //}
        }

        private bool NeedGetAvailableQty(SHFastShipLine line)
        {
            if (line.OriginalData.WHKey == null && line.WHKey != null) return true;
            if (line.OriginalData.WHKey.ID != line.WHKey.ID) return true;
            return false;
        }

        private bool NeedGetPrice(SHFastShipLine line)
        {
            if (line.SOLineKey != null) return false;
            if (this.CustomerKey.ID != this.OriginalData.CustomerKey.ID) return true;
            if (line.OriginalData.ItemKey == null) return true;
            if (line.ItemKey.ID != line.OriginalData.ItemKey.ID) return true;
            //if (line.Qty != line.OriginalData.Qty) return true;
            return false;
        }

        private bool NeedGetMoney(SHFastShipLine line)
        {
            if (line.SOLineKey == null)
            {
                if (this.CustomerKey.ID != this.OriginalData.CustomerKey.ID) return true;
                if (line.OriginalData.ItemKey == null) return true;
                if (line.ItemKey.ID != line.OriginalData.ItemKey.ID) return true;
                if (line.Qty != line.OriginalData.Qty) return true;
            }
            else
            {
                if (line.Qty != line.OriginalData.Qty) return true;
            }
            return false;
        }

		/// <summary>
		/// after Update
		/// </summary>
        protected override void OnUpdated()
        {
            base.OnUpdated();
            // TO DO: write your business code here...
            using (ISession session = Session.Open())
            {
                List<string> batchsql = new List<string>();

                if (this.DocState == FastShipDocState.DocOpen)
                {
                    //开立单据修改
                    //更新Kit子件，并占用库存
                    List<SHFastShipLine> updatelines = new List<SHFastShipLine>();
                    List<SHFastShipLine> deletelines=new List<SHFastShipLine>();

                    string sql = "";

                    foreach (SHFastShipLine line in this.SHFastShipLine)
                    {
                        if (line.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
                        {
                            if (line.KitInfoChange())
                            {
                                updatelines.Add(line);
                            }
                        }
                        else
                        {
                            if (line.ReserveInfoChange())
                            {
                                if (line.OriginalData.ItemKey != null)
                                {
                                    long lotid0 = 0;
                                    if (line.OriginalData.LotMasterKey != null) lotid0 = line.OriginalData.LotMasterKey.ID;
                                    sql = BuildReserveSQL(line.OriginalData.ItemKey.ID, line.OriginalData.WHKey.ID, lotid0
                                        , line.OriginalData.Qty * -1);
                                    batchsql.Add(sql);
                                }

                                long lotid1 = 0;
                                if (line.LotMasterKey != null) lotid1 = line.LotMasterKey.ID;
                                sql = BuildReserveSQL(line.ItemKey.ID, line.WHKey.ID, lotid1, line.Qty);
                                batchsql.Add(sql);
                            }
                        }
                    }

                    foreach (SHFastShipLine line in this.SHFastShipLine.DelLists)
                    {
                        if (line.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
                        {
                            deletelines.Add(line);
                        }
                        else
                        {
                            long lotid1 = 0;
                            if (line.LotMasterKey != null) lotid1 = line.LotMasterKey.ID;
                            sql = BuildReserveSQL(line.ItemKey.ID, line.WHKey.ID, lotid1, line.Qty*-1);
                            batchsql.Add(sql);
                        }
                    }

                    if (deletelines.Count > 0)
                    {
                        BatchDeleteKitItem(deletelines, ref batchsql);
                    }

                    if (updatelines.Count > 0)
                    {
                        BatchDeleteKitItem(updatelines, ref batchsql);
                        BatchCreateKitItem(updatelines, ref batchsql);
                    }

                }


                //单据 审核、弃审 处理库存占用
                if ((this.DocState == FastShipDocState.DocAudited
                        && this.OriginalData.DocState == FastShipDocState.DocOpen)
                    ||(this.DocState == FastShipDocState.DocHold
                        && this.OriginalData.DocState == FastShipDocState.DocOpen)
                    || (this.DocState == FastShipDocState.DocClose
                        && this.OriginalData.DocState == FastShipDocState.DocOpen))
                {
                    //单据审核、挂起、关闭
                    foreach (SHFastShipLine line in this.SHFastShipLine)
                    {
                        BuildReserveLineSQL(line,false, ref batchsql);
                    }
                }
                else if ((this.DocState == FastShipDocState.DocOpen
                        && this.OriginalData.DocState == FastShipDocState.DocAudited)
                    ||(this.DocState == FastShipDocState.DocOpen
                        && this.OriginalData.DocState == FastShipDocState.DocHold))
                {
                    //单据弃审、取消挂起
                    foreach (SHFastShipLine line in this.SHFastShipLine)
                    {
                        BuildReserveLineSQL(line,true, ref batchsql);
                    }
                }

                BatchRunSQL(batchsql);

                BatchUpdateSOLine();

                session.Commit();
            }
        }

        private void BatchUpdateSOLine()
        {
            foreach (SHFastShipLine line in this.SHFastShipLine.DelLists)
            {
                line.UpdateSOLine();
            }

            foreach (SHFastShipLine line in this.SHFastShipLine)
            {
                line.UpdateSOLine();
            }

            
        }

        public void BuildReserveLineSQL(SHFastShipLine line, bool flag,ref List<string> batchsql)
        {
            int ratio = 1;
            if (flag == false)
                ratio = -1;

            if (line.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
            {
                SHFastShipKitItem.EntityList items = SHFastShipKitItem.Finder.FindAll("SHFastShipLine=" + line.ID, null);
                foreach (SHFastShipKitItem item in items)
                {
                    long lotid = 0;
                    if (line.LotMasterKey != null) lotid = line.LotMasterKey.ID;
                    string sql = BuildReserveSQL(item.ItemKey.ID, item.WHKey.ID, lotid, item.Qty * ratio);
                    batchsql.Add(sql);
                }
            }
            else
            {
                long lotid = 0;
                if (line.LotMasterKey != null) lotid = line.LotMasterKey.ID;
                string sql = BuildReserveSQL(line.ItemKey.ID, line.WHKey.ID, lotid, line.Qty * ratio);
                batchsql.Add(sql);
            }
        }

        private void BatchDeleteKitItem(List<SHFastShipLine> lines, ref List<string> batchsql)
        {
            foreach (SHFastShipLine line in lines)
            {
                if (line.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
                {
                    SHFastShipKitItem.EntityList items = SHFastShipKitItem.Finder.FindAll("SHFastShipLine=" + line.ID, null);
                    foreach (SHFastShipKitItem item in items)
                    {
                        long lotid = 0;
                        if (line.LotMasterKey != null) lotid = line.LotMasterKey.ID;
                        string sql=BuildReserveSQL(item.ItemKey.ID, item.WHKey.ID, lotid, item.Qty * -1);
                        batchsql.Add(sql);
                        item.Remove();
                    }
                }
            }
        }


		/// <summary>
		/// before Delete
		/// </summary>
		protected override void OnDeleting() {
			base.OnDeleting();
			// TO DO: write your business code here...
            if (this.DocState == FastShipDocState.DocAudited)
                throw new Exception("已审单据,不能修改!");
		}

		/// <summary>
		/// after Delete
		/// </summary>
		protected override void OnDeleted() {
			base.OnDeleted();
			// TO DO: write your business code here...
            using (ISession session = Session.Open())
            {
                List<string> batchsql = new List<string>();
                List<SHFastShipLine> lines = new List<SHFastShipLine>();

                foreach (SHFastShipLine line in this.SHFastShipLine.DelLists)
                {
                    if (line.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
                    {
                        lines.Add(line);
                    }
                    else
                    {
                        long lotid = 0;
                        if (line.LotMasterKey != null) lotid = line.LotMasterKey.ID;
                        string sql=BuildReserveSQL(line.ItemKey.ID, line.WHKey.ID, lotid, line.Qty * -1);
                        batchsql.Add(sql);
                    }
                }

                BatchDeleteKitItem(lines,ref batchsql);
                BatchRunSQL(batchsql);

                BatchUpdateSOLine();

                session.Commit();
            }
		}

		/// <summary>
		/// on Validate
		/// </summary>
		protected override void OnValidate() {
			base.OnValidate();
			this.SelfEntityValidator();
			// TO DO: write your business code here...
            if (this.SHFastShipLine.Count <= 0)
                throw new Exception("单据行不能为空！");

            if (this.IsZY == true && (this.ZYCustomerKey == null || this.ZYCustomerKey.ID <= 0))
                throw new Exception("直运客户不能为空！");

            if (this.Customer.DescFlexField.PrivateDescSeg3 == "True" && !this.DocType.Name.Contains("办事处"))
                throw new Exception("客户为办事处，请选择办事处单据类型！");
            if (this.Customer.DescFlexField.PrivateDescSeg3 != "True" && this.DocType.Name.Contains("办事处"))
                throw new Exception("客户不为办事处，请选择其他单据类型！");
            if (this.Org.Code == "1000" && this.Customer.DescFlexField.PrivateDescSeg7 == "True" && this.SaleWHKey == null)
                throw new Exception("请选择总经销仓库！");

            //交验行客户同头客户相同
            foreach (SHFastShipLine line in this.SHFastShipLine)
            {
                if (line.SOLineKey != null)
                {
                    if (this.Customer.DescFlexField.PrivateDescSeg8 == "True")
                    {
                        //下线客户
                        if (line.SOLine.DescFlexField.PubDescSeg40 != this.Customer.Code)
                            throw new Exception("行号："+line.DocLineNo+"下线客户同单头客户不同，不能保存！");
                    }
                    else
                    {
                        //非下线客户
                        if (line.SOLine.SO.OrderBy.CustomerKey.ID != this.CustomerKey.ID)
                            throw new Exception("行号:" + line.DocLineNo + "客户同单头客户不同，不能保存！");
                    }
                }
            }

            //淘宝校验
            if (this.Customer.DescFlexField.PrivateDescSeg4 == "淘宝店")
            {
                if (this.DocType.Code != "U914")
                    throw new Exception("客户为淘宝店，请选择淘宝单据类型");
            }
            if (this.DocType.Code == "U914")
            {
                if (this.Customer.DescFlexField.PrivateDescSeg4 != "淘宝店")
                    throw new Exception("单据类型为淘宝，请选择淘宝客户！");
                if (string.IsNullOrEmpty(this.TBDocNo)) 
                    throw new Exception("淘宝发货，淘宝单号必须录入！");
                if (string.IsNullOrEmpty(this.FinalCustomer))
                    throw new Exception("淘宝发货,消费者必须录入！");

                if (this.IsZT == false)
                    if (this.AgencyKey == null || this.GeneralAgencyKey == null)
                        throw new Exception("非直提业务，必须录入总经销商、经销商！");

                foreach (SHFastShipLine line in this.SHFastShipLine)
                {
                    if (line.FinalAmount <= 0) throw new Exception("行：" + line.DocLineNo + "必须录入最终价！");
                    //decimal total = line.TBFee + line.ZMDProfit + line.ZDLProfit + line.GSProfit + line.GSTransportFee;
                    //if (total != line.FinalAmount * line.DevideRatio)
                    //    throw new Exception("行：" + line.DocLineNo + "最终成交金额不等于各分成相加[" + total + "]！");
                }
            }
		}
		#endregion
		
		#region 异常处理，开发人员可以重新封装异常
		public override void  DealException(Exception e)
        	{
          		base.DealException(e);
          		throw e;
        	}
		#endregion

		#region  扩展属性代码区
		
		#endregion

		#region CreateDefault
		private static SHFastShip CreateDefault_Extend() {
			//TODO delete next code and add your custome code here
			throw new NotImplementedException () ;
		}
		/// <summary>
		/// Create DefaultComponent
		/// </summary>
		/// <returns>DefaultComponent Instance</returns>
		private  static SHFastShip CreateDefaultComponent_Extend(){
			//TODO delete next code and add your custome code here
			throw new NotImplementedException () ;
		}
		
		#endregion 






		#region Model Methods
		#endregion		
	}
}
